package middleware

import (
	"go-web/config"
	"go-web/model"
	"log"
	"net/http"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// Auth 授权中间件 -- cookie
func Auth() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 通过 context.Request.Cookie() 获取 cookie
		cookie, e := context.Request.Cookie("user_cookie")

		log.Println(cookie)

		if e == nil {
			// 刷新 cookie: 在 cookie 请求成功的时候自动刷新我们的 cookie 时间。
			context.SetCookie(
				cookie.Name,
				cookie.Value,
				1000,
				cookie.Path,
				cookie.Domain,
				cookie.Secure,
				cookie.HttpOnly,
			)
			context.Next()
		} else {
			// context.Abort 表示对当前的请求进行中止
			context.Abort()
			context.HTML(http.StatusUnauthorized, "401.tmpl", nil)
		}
	}
}

// JwtAuth Jwt 鉴权
func JwtAuth() gin.HandlerFunc {
	return func(context *gin.Context) {
		result := model.Result{
			Code:    http.StatusUnauthorized,
			Message: "无法认证，重新登录",
			Data:    nil,
		}

		auth := context.Request.Header.Get("Authorization")

		if len(auth) == 0 {
			context.Abort()
			context.JSON(result.Code, result)
		}

		auth = strings.Fields(auth)[1]
		// 校验 token
		_, err := parseToken(auth)
		if err != nil {
			context.Abort()
			result.Message = "token 过期" + err.Error()
			context.JSON(result.Code, result)
		} else {
			println("token 正确")
		}

		// 中间件继续往下一级
		context.Next()
	}
}

// 解析 jwt token
func parseToken(token string) (*jwt.StandardClaims, error) {
	jwtToken, err := jwt.ParseWithClaims(
		token,
		&jwt.StandardClaims{},
		func(token *jwt.Token) (i interface{}, e error) {
			return []byte(config.Secret), nil
		},
	)

	if err == nil && jwtToken != nil {
		if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid {
			return claim, nil
		}
	}

	return nil, err
}
